package com.qf.fronted.controller;

import com.alibaba.fastjson.JSONObject;
import com.qf.admin.domain.User;
import com.qf.commons.Data;
import com.qf.fronted.service.ICartService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * 同步购物车数据：
 * 1. 用户登录成功之后，同步购物车数据
 * 2. 在购物车页面删除购物车数据。
 * 3. 在首页中添加商品到购物车。
 * 4. 在购物车页面，"+" "-" 商品。
 */
@RestController
@CrossOrigin("*")
@RequestMapping(value = "/sync-cart", name = "FrontedSyncCartDataServlet")
public class SyncCartDataController {

    private ICartService cartService;

    public SyncCartDataController(ICartService cartServiceImpl) {
        this.cartService = cartServiceImpl;
    }

    /***
     * 添加商品到购物车, 首页中点击添加按钮
     * @param req
     * @throws ServletException
     * @throws IOException
     */
    @PostMapping("/addGood")
    public Data addGood(String goodId, HttpServletRequest req) {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        Integer userId = user.getId();
        Data data = null;
        try {
            cartService.addGood(userId, Integer.parseInt(goodId));
            data = new Data(1, "success");
        } catch (Exception ex) {
            ex.printStackTrace();
            data = new Data(-1, "添加到购物车失败");
        }
        return data;

    }

    /**
     * 在购物车页面，当用户点击 ‘+’ 和 ‘-’ 的时候触发的，就是用户要去改变商品的数量
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @PostMapping("/changeGoodNum")
    public Data changeGoodNum(String goodId, String num, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        System.out.println(user);
        Integer userId = user.getId();

        Data data = null;
        try {
            cartService.updateGoodNum(userId, Integer.parseInt(goodId), Integer.parseInt(num));
            data = new Data(1, "success");
        } catch (Exception ex) {
            ex.printStackTrace();
            data = new Data(-1, "更新购物车失败");
        }
        return data;
    }

    /**
     * 该方法在购物车页面，用户点击删除的时候触发。
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @PostMapping("/removeGood")
    private void removeGood(String goodId, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        Integer userId = user.getId();

        cartService.deleteCartData(userId, Integer.parseInt(goodId));
    }

    /**
     * 用户登录成功之后，需要将前端的购物车数据与服务器端合并：
     * 1.前端购物车没有数据。
     * 2.前端购物车有数据。 求并集，并以浏览器为准 ： {1， 2， 3}   {2, 5, 6}  -> {1, 2, 3, 5, 6}
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @PostMapping("/getCartInfo")
    private Data getCartInfo(String cartData, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        Integer userId = user.getId();
        Data data = null;
        if (null != cartData && !"".equals(cartData.trim())) {
            // 表示前端购物车有数据，那么就需要与服务端对应的购物车进行合并
            // browserShoppingCartData: {1001: 3, 1002: 1, 1013: 2}, JSONObject.parseObject是将json
            // 字符串转换为java对象
            Map<String, Integer> cartDates = JSONObject.parseObject(cartData, Map.class);
            cartService.mergeCartData(cartDates, userId);

            Map<String, Integer> map = cartService.getCartInfoOfUser(userId);

            data = new Data(1, "购物车中y数据,数据库有");
            data.setObj(map);

        } else {
            Map<String, Integer> map = cartService.getCartInfoOfUser(userId);

            if (map.size() == 0) {
                data = new Data(-2, "购物车中没有数据");
            } else {
                data = new Data(1, "购物车中无数据,数据库有");
                data.setObj(map);  // {code: 1, msg:'', obj: {}}
            }
            return data;
        }
        return data;
    }

}
